package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.enums.PayType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwEnterpriseInfo;
import com.ruoyi.system.domain.GwPlatformRights;
import com.ruoyi.system.service.WeChatPayService;
import com.ruoyi.system.utils.AlipayUtil;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.GwPlatformServiceOrderMapper;
import com.ruoyi.system.domain.GwPlatformServiceOrder;
import com.ruoyi.system.service.IGwPlatformServiceOrderService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 平台服务订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-09
 */
@Service
public class GwPlatformServiceOrderServiceImpl implements IGwPlatformServiceOrderService 
{
    private static final Logger log = LoggerFactory.getLogger(GwPlatformServiceOrderServiceImpl.class);
    @Resource
    private GwPlatformServiceOrderMapper gwPlatformServiceOrderMapper;
    @Resource
    private WeChatPayService wxChatPayService;
    @Value("${wx.pay.serviceNotifyUrl}")
    private String serviceNotifyUrl;

    @Value("${alipay.serviceNotifyUrl}")
    private String alipayServiceReturnUrl;

    @Value("${alipay.serviceReturnUrl}")
    private String alipayServiceNotifyUrl;

    @Autowired
    private AlipayUtil alipayUtil;

    /**
     * 查询平台服务订单
     * 
     * @param id 平台服务订单主键
     * @return 平台服务订单
     */
    @Override
    public GwPlatformServiceOrder selectGwPlatformServiceOrderById(String id)
    {
        return gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderById(id);
    }

    /**
     * 查询平台服务订单列表
     * 
     * @param gwPlatformServiceOrder 平台服务订单
     * @return 平台服务订单
     */
    @Override
    public List<GwPlatformServiceOrder> selectGwPlatformServiceOrderList(GwPlatformServiceOrder gwPlatformServiceOrder)
    {
        if(StringUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            gwPlatformServiceOrder.setEnterprise(SecurityUtils.getLoginUser().getEnterpriseId());
        }
        if(StringUtils.isNotEmpty(gwPlatformServiceOrder.getStatus()) && gwPlatformServiceOrder.getStatus().equals("0")){
            gwPlatformServiceOrder.setStatus(null);
        }
        return gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderList(gwPlatformServiceOrder);
    }

    /**
     * 新增平台服务订单
     * 
     * @param gwPlatformServiceOrder 平台服务订单
     * @return 结果
     */
    @Override
    public int insertGwPlatformServiceOrder(GwPlatformServiceOrder gwPlatformServiceOrder)
    {
        gwPlatformServiceOrder.setId(IdUtils.fastSimpleUUID());
        gwPlatformServiceOrder.setCreateBy(SecurityUtils.getUserId()+"");
        gwPlatformServiceOrder.setCreateTime(DateUtils.getNowDate());
        gwPlatformServiceOrder.setOrderNumber(createOrderNumber());
        int num = gwPlatformServiceOrderMapper.insertGwPlatformServiceOrder(gwPlatformServiceOrder);
        return num;
    }

    /**
     * 修改平台服务订单
     * 
     * @param gwPlatformServiceOrder 平台服务订单
     * @return 结果
     */
    @Override
    public int updateGwPlatformServiceOrder(GwPlatformServiceOrder gwPlatformServiceOrder)
    {
        gwPlatformServiceOrder.setUpdateTime(DateUtils.getNowDate());
        gwPlatformServiceOrder.setUpdateBy(SecurityUtils.getUserId()+"");
        return gwPlatformServiceOrderMapper.updateGwPlatformServiceOrder(gwPlatformServiceOrder);
    }

    /**
     * 批量删除平台服务订单
     * 
     * @param ids 需要删除的平台服务订单主键
     * @return 结果
     */
    @Override
    public int deleteGwPlatformServiceOrderByIds(String[] ids)
    {
        return gwPlatformServiceOrderMapper.deleteGwPlatformServiceOrderByIds(ids);
    }

    /**
     * 删除平台服务订单信息
     * 
     * @param id 平台服务订单主键
     * @return 结果
     */
    @Override
    public int deleteGwPlatformServiceOrderById(String id)
    {
        return gwPlatformServiceOrderMapper.deleteGwPlatformServiceOrderById(id);
    }

    /***
     * 查询登录人所在企业服务订单列表
     * @Date 上午 11:30:15 2025/5/28
     * @param gwPlatformServiceOrder
     * @return 结果
     **/
    @Override
    public List<GwPlatformServiceOrder> myEnterpriseList(GwPlatformServiceOrder gwPlatformServiceOrder) {
        List<GwPlatformServiceOrder> orderList = Lists.newArrayList();
        if(StringUtils.isBlank(SecurityUtils.getLoginUser().getEnterpriseId())){
            return orderList;
        }

        gwPlatformServiceOrder.setEnterprise(SecurityUtils.getLoginUser().getEnterpriseId());
        return gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderList(gwPlatformServiceOrder);
    }

    /**
     * 取消订单
     * @Date 下午 1:16:32 2025/5/28
     * @param gwPlatformServiceOrder
     * @return int
     **/
    @Override
    public int cancelOrder(GwPlatformServiceOrder gwPlatformServiceOrder) {
        GwPlatformServiceOrder order = new GwPlatformServiceOrder();
        order.setId(gwPlatformServiceOrder.getId());
        order.setStatus(OrderStatus.CANCEL.getCode());
        order.setUpdateTime(new Date());
        order.setUpdateBy(SecurityUtils.getUserId()+"");

        return gwPlatformServiceOrderMapper.updateGwPlatformServiceOrder(order);
    }
    /**
     * @Author haiyue
     * @Description
     * @Date 下午 1:24:56 2025/5/28
     * @param gwPlatformServiceOrder
     * @return 结果
     **/
    @Override
    public AjaxResult payOrder(GwPlatformServiceOrder gwPlatformServiceOrder) {
        GwPlatformServiceOrder originOrder = gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderById(gwPlatformServiceOrder.getId());
        if (gwPlatformServiceOrder.getPayType().equals(PayType.WEI_XIN.getCode())){

            String codeUrl =  wxChatPayService.createNativePayOrder(originOrder.getId(), originOrder.getServiceFee().multiply(new BigDecimal(100)).intValue(),
                    originOrder.getServiceDescription(), serviceNotifyUrl);
            log.info("平台服务调用微信扫码支付预下单接口 订单orderId为 {} 微信扫码下单返回结果 {} ：",gwPlatformServiceOrder.getId(),codeUrl);
            return AjaxResult.success(codeUrl);
        }else if(gwPlatformServiceOrder.getPayType().equals(PayType.ZHI_FU_BAO.getCode())){
            String form = null;
            try {
                form = alipayUtil.createPayPage(originOrder.getId(), "平台服务交易", String.valueOf(originOrder.getServiceFee()),alipayServiceReturnUrl,alipayServiceNotifyUrl);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            return AjaxResult.success(form);
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult appletPayOrder(GwPlatformServiceOrder gwPlatformServiceOrder) {

        GwPlatformServiceOrder originOrder = gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderById(gwPlatformServiceOrder.getId());

            Map<String,String> paramsMap = null;
            try {
                paramsMap = wxChatPayService.createAppletPrepayOrder(gwPlatformServiceOrder.getId(), originOrder.getServiceFee().multiply(new BigDecimal(100)).intValue(),
                        originOrder.getServiceDescription(), serviceNotifyUrl,gwPlatformServiceOrder.getOpenId());
            } catch (IOException e) {
                log.error("系统出现异常:{}",e.getMessage());
                return AjaxResult.error("系统出现异常，请稍后再试！");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            log.info("平台服务调用微信小程序支付预下单接口 订单orderId为 {} 微信扫码下单返回结果 {} ：",gwPlatformServiceOrder.getId(), JSON.toJSONString(paramsMap));
            return AjaxResult.success(paramsMap);

    }

    @Override
    public AjaxResult statisticsServiceOrder() {
        AjaxResult result = new AjaxResult();
        int waitPayCount = 0;
        int payCount = 0;
        if(!StringUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            GwPlatformServiceOrder old = new GwPlatformServiceOrder();
            old.setEnterprise(SecurityUtils.getLoginUser().getEnterpriseId());
            List<GwPlatformServiceOrder> orderList = gwPlatformServiceOrderMapper.selectGwPlatformServiceOrderList(old);
            if(!CollectionUtils.isEmpty(orderList)){
                List<GwPlatformServiceOrder> waitList = orderList.stream().filter(item->item.getStatus().equals(OrderStatus.WAIT.getCode())).collect(Collectors.toList());
                List<GwPlatformServiceOrder> payList = orderList.stream().filter(item->item.getStatus().equals(OrderStatus.PAY.getCode())).collect(Collectors.toList());
                waitPayCount = waitList.size();
                payCount = payList.size();
            }
        }
        result.put("waitPayCount",waitPayCount);
        result.put("payCount",payCount);
        return result;
    }

    @Override
    public int updateOrder(GwPlatformServiceOrder serviceOrder) {
        serviceOrder.setUpdateTime(DateUtils.getNowDate());
        return gwPlatformServiceOrderMapper.updateGwPlatformServiceOrder(serviceOrder);
    }

    private String createOrderNumber(){
        String orderNumber = "F";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String time = sdf.format(new Date());
        orderNumber=orderNumber+time;
        //4位随机数
        Random random = new Random();
        int min = 1000;
        int max = 9999;
        int randomNum = random.nextInt(max - min + 1) + min;
        orderNumber = orderNumber+randomNum;
        return orderNumber;
    }
}
